//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
//

#include "MobiSenseBroker.h"

#include <UnderlayConfigurator.h>
#include "lbr/CycleTargetArea.h"
#include "lbr/Coordinates.h"

#include "MobiSenseAppMessage_m.h"

#include "NodeHandle.h"
#include "OverlayKey.h"


using namespace std;

Define_Module(MobiSenseBroker);

void MobiSenseBroker::initializeApp(int stage)
{
    if (stage != MIN_STAGE_APP) {
        return;
    }

    interval = par("interval");

    if(hasPar("bsub"))
    	bsub = par("bsub").boolValue();
    else
    	bsub = false;

    if(bsub){
    	timer = new cMessage("timer");
    	scheduleAt( simTime() + interval, timer );
    }

}

void MobiSenseBroker::finishApp()
{
}

void MobiSenseBroker::handleTimerEvent( cMessage* msg )
{
    if( msg == timer ) {

    	scheduleAt( simTime() + interval, timer );

    	if (this->underlayConfigurator->isInInitPhase()) return;


    	MobiSenseAppSub* submsg = new MobiSenseAppSub("subscription");
    	Coordinates coord(80.0, 80.0);
    	CycleTargetArea *area = new CycleTargetArea(coord, 10);
    	submsg->setArea(*area);
    	submsg->setEid(1);
    	submsg->setType(MOBISENSE_APP_SUB);
    	submsg->setBitLength(MOBISENSEAPP_SUB_L(submsg));
    	handleSubPrimitive(submsg);

    }else{
    	delete msg;
    }
}

void MobiSenseBroker::handleSubPrimitive(MobiSenseAppSub *msg)
{
	this->sendMessageToLowerTier(msg);
}

void MobiSenseBroker::handlePubPrimitive(MobiSenseAppPub *msg)
{
	this->sendMessageToLowerTier(msg);
}




